<template>
  <view class="schedule-container">
    <!-- 医生信息 -->
    <view class="doctor-info">
      <image :src="doctor.avatar || '/static/default-doctor.png'" class="avatar"></image>
      <view class="info">
        <view class="name">{{ doctor.name }}</view>
        <view class="specialty">{{ doctor.specialty }}</view>
      </view>
    </view>

    <!-- 日期选择 -->
    <view class="date-list">
      <view 
        class="date-item" 
        v-for="(date, index) in dates" 
        :key="index"
        :class="{ active: currentDateIndex === index }"
        @tap="selectDate(index)"
      >
        <text class="day">{{ formatDay(date) }}</text>
        <text class="date">{{ formatDate(date) }}</text>
      </view>
    </view>

    <!-- 时间段选择 -->
    <view class="time-period">
      <view class="title">选择时间段</view>
      <view class="period-list">
        <view 
          class="period-item"
          v-for="period in availablePeriods"
          :key="period.time"
          :class="{ 
            active: selectedPeriod === period.time,
            disabled: period.availableSlots <= 0 
          }"
          @tap="selectPeriod(period)"
        >
          <text class="time">{{ period.label }}</text>
          <text class="slots">剩余号源: {{ period.availableSlots }}</text>
        </view>
      </view>
    </view>

    <!-- 预约按钮 -->
    <view class="bottom-button">
      <button 
        class="submit-btn" 
        :disabled="!canSubmit"
        @tap="submitAppointment"
      >
        确认预约
      </button>
    </view>
  </view>
</template>

<script>
import { getDoctorById } from '@/api/doctor'
import { getDoctorSchedule, createAppointment } from '@/api/schedule'
import { createNotification } from '@/api/notification'

export default {
  data() {
    return {
      doctor: {},
      dates: [],          
      schedules: [],      
      currentDateIndex: 0,
      selectedPeriod: ''
    }
  },

  methods: {
    // 格式化星期
    formatDay(date) {
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      return days[date.getDay()]
    },

    // 格式化日期显示
    formatDate(date) {
      return `${date.getMonth() + 1}月${date.getDate()}日`
    },

    // 格式化日期为后端需要的格式 (YYYY-MM-DD)
    formatDateString(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 选择日期
    selectDate(index) {
      this.currentDateIndex = index
      this.selectedPeriod = ''  // 重置时间段选择
    },

    // 选择时间段
    selectPeriod(period) {
      if (period.availableSlots <= 0) return
      this.selectedPeriod = period.time
    },

    // 获取医生信息
    async getDoctorInfo(id) {
      try {
        const res = await getDoctorById(id)
        this.doctor = res
      } catch (error) {
        console.error('获取医生信息失败：', error)
        uni.showToast({
          title: '获取医生信息失败',
          icon: 'none'
        })
      }
    },

    // 获取医生排班信息
    async getScheduleInfo(doctorId) {
      try {
        const res = await getDoctorSchedule(doctorId)
        this.schedules = Array.isArray(res) ? res : []
        this.initAvailableDates()
      } catch (error) {
        console.error('获取排班信息失败：', error)
        this.schedules = []
        uni.showToast({
          title: '获取排班信息失败',
          icon: 'none'
        })
      }
    },

    // 初始化可预约日期
    initAvailableDates() {
      const today = new Date()
      const todayStr = this.formatDateString(today)
      
      const availableDates = this.schedules
        .filter(s => s.scheduleDate >= todayStr)
        .map(s => s.scheduleDate)
      
      const uniqueDates = [...new Set(availableDates)]
      uniqueDates.sort()
      
      const recentDates = uniqueDates.slice(0, 3)
      this.dates = recentDates.map(dateStr => new Date(dateStr))
      
      if (this.dates.length === 0) {
        uni.showToast({
          title: '暂无可预约时间',
          icon: 'none'
        })
      }
    },

    // 提交预约
    async submitAppointment() {
      if (!this.canSubmit) return
      
      try {
        const userId = uni.getStorageSync('userId')
        // 创建预约
        const appointmentRes = await createAppointment({
          user_id: userId,
          doctor_id: this.doctor.id,
          appointment_date: this.formatDateString(this.dates[this.currentDateIndex]),
          appointment_time: this.selectedPeriod
        })
        
        // 创建预约成功通知，简化参数
        await createNotification({
          userId: userId,
          title: '预约成功通知',
          content: `您已成功预约${this.doctor.name}医生的门诊`
        })
        
        uni.showToast({
          title: '预约成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        uni.showToast({
          title: error.message || '预约失败',
          icon: 'none'
        })
      }
    }
  },

  computed: {
    // 当前选中日期的可用时间段
    availablePeriods() {
      if (!this.dates[this.currentDateIndex]) {
        return []
      }
      
      const currentDate = this.dates[this.currentDateIndex]
      const dateStr = this.formatDateString(currentDate)
      
      // 获取当天的排班记录
      const daySchedules = this.schedules.filter(s => 
        s.scheduleDate === dateStr
      )
      
      return [
        {
          time: 'morning',
          label: '上午',
          availableSlots: daySchedules.find(s => s.timePeriod === 'morning')?.availableSlots || 0
        },
        {
          time: 'afternoon',
          label: '下午',
          availableSlots: daySchedules.find(s => s.timePeriod === 'afternoon')?.availableSlots || 0
        }
      ]
    },

    // 是否可以提交预约
    canSubmit() {
      if (!this.dates[this.currentDateIndex] || !this.selectedPeriod) {
        return false
      }
      
      const currentDate = this.dates[this.currentDateIndex]
      const dateStr = this.formatDateString(currentDate)
      const currentSchedule = this.schedules.find(s => 
        s.scheduleDate === dateStr && 
        s.timePeriod === this.selectedPeriod
      )
      
      return currentSchedule && currentSchedule.availableSlots > 0
    }
  },

  onLoad(options) {
    const doctorId = options.id
    if (!doctorId) {
      console.error('未接收到医生ID')
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      })
      return
    }
    
    this.getDoctorInfo(doctorId)
    this.getScheduleInfo(doctorId)
  }
}
</script>

<style lang="scss">
.schedule-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
  
  .doctor-info {
    display: flex;
    align-items: center;
    padding: 30rpx;
    background: #fff;
    margin-bottom: 20rpx;
    
    .avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 60rpx;
      margin-right: 24rpx;
    }
    
    .info {
      .name {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .specialty {
        font-size: 28rpx;
        color: #666;
      }
    }
  }
  
  .date-list {
    background: #fff;
    padding: 30rpx;
    
    .date-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 100rpx;
      padding: 0 30rpx;
      margin-bottom: 20rpx;
      border-radius: 8rpx;
      border: 2rpx solid #eee;
      
      &.active {
        background: #e6f3ff;
        border-color: #007AFF;
        
        .day, .date, .remaining {
          color: #007AFF;
        }
      }
      
      .day {
        font-size: 28rpx;
        color: #333;
      }
      
      .date {
        font-size: 28rpx;
        color: #666;
      }
      
      .remaining {
        font-size: 26rpx;
        color: #999;
      }
    }
  }
  
  .time-period {
    background: #fff;
    padding: 30rpx;
    margin-bottom: 20rpx;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .period-list {
      display: flex;
      flex-wrap: wrap;
      
      .period-item {
        width: 45%;
        margin: 10rpx;
        padding: 20rpx;
        background: #fff;
        border-radius: 8rpx;
        border: 2rpx solid #eee;
        text-align: center;
        
        &.active {
          background: #e6f3ff;
          border-color: #007AFF;
          
          .time, .slots {
            color: #007AFF;
          }
        }
        
        &.disabled {
          background: #ccc;
          pointer-events: none;
          
          .time, .slots {
            color: #999;
          }
        }
        
        .time {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .slots {
          font-size: 26rpx;
          color: #666;
        }
      }
    }
  }
  
  .bottom-button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 30rpx;
    background: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .submit-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      background: #007AFF;
      color: #fff;
      font-size: 30rpx;
      border-radius: 40rpx;
      
      &[disabled] {
        background: #ccc;
      }
    }
  }
}
</style> 